package fun.ticsmyc.multiThread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Ticsmyc
 * @date 2020-12-10 10:49
 */
public class 三线程synchronized {


    /**
     * 锁句柄
     * 所有wait notify操作都由它执行
     */
    private static final Object lock1 = new Object();

    /**
     * wait-notify不能精确唤醒，只能唤醒所有线程
     * 所以必须有一个flag，用来指示当前线程是否满足了工作条件
     */
    private static int flag =1;

    public static void main(String[] args) {
        Runnable task1 = ()->{
            while(true){
                synchronized (lock1){
                    while(flag != 1){
                        try {
                            lock1.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("线程1 唤醒 检测");
                    }
                    System.out.println("线程1"+" "+ Thread.currentThread().getName());
                    flag=2;
                    lock1.notifyAll();
                }
            }

        };
        Runnable task2= ()->{
            while(true){
                synchronized (lock1){
                    while(flag != 2){
                        try {
                            lock1.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("线程2 唤醒 检测");
                    }
                    System.out.println("线程2"+" "+ Thread.currentThread().getName());
                    flag=3;
                    lock1.notifyAll();
                }
            }

        };
        Runnable task3 = ()->{
            while(true){
                synchronized (lock1){
                    while(flag != 3){
                        try {
                            lock1.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("线程3 唤醒 检测");
                    }
                    System.out.println("线程3"+" "+ Thread.currentThread().getName());
                    flag=1;
                    lock1.notifyAll();
                }
            }

        };

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.submit(task1);
        executorService.submit(task2);
        executorService.submit(task3);

    }
}
